package top.hkyzf.study.leetcode.tree;

import org.junit.Test;

/**
 * @author 朱峰
 * @date 2022-2-22 14:44
 */
public class 路径总和_112 {
    private boolean mark = false;
    public boolean hasPathSum(TreeNode root, int targetSum) {
        int resultSum = 0;
        dfs(root, resultSum, targetSum);
        return mark;
    }

    void dfs(TreeNode root, int resultSum, int targetSum) {
        if (!mark) {
            if (root == null) {
                return;
            }
            resultSum += root.val;
            if (root.left == null && root.right == null) {
                if (resultSum == targetSum) {
                    mark = true;
                }
            }
            dfs(root.left, resultSum, targetSum);
            dfs(root.right, resultSum, targetSum);
        }
    }

    @Test
    public void testHasPathSum () {
        TreeNode node8 = new TreeNode(1);
        TreeNode node7 = new TreeNode(2);
        TreeNode node6 = new TreeNode(7);
        TreeNode node5 = new TreeNode(4, null, node8);
        TreeNode node4 = new TreeNode(13);
        TreeNode node3 = new TreeNode(11, node6, node7);
        TreeNode node2 = new TreeNode(8, node4, node5);
        TreeNode node1 = new TreeNode(4, node3, null);
        TreeNode root = new TreeNode(5, node1, node2);
        int targetSum = 22;
        System.out.println(hasPathSum(root, targetSum));
    }
}
